package cn.jdy.plugins.wap;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.IpUtil;
import cn.jdy.payment.service.OrderService;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.CollectPK;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.BusinessService;
import cn.jdy.plugins.service.CollectService;
import cn.jdy.plugins.service.IPRecordService;

/**
 * @author wuzhiliang
 * @title 商机信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/business")
public class BusinessCtrl extends BaseCtrl {

  @Autowired
  private ConfService confService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private CollectService collectService;
  @Autowired
  private BusinessService businessService;
  @Autowired
  private IPRecordService ipRecordService;

  /**
   * 商机详细内容页面
   *
   * @param id
   * @return
   */
  @RequestMapping("")
  public ModelAndView list(Business entity, String title) {
    ModelAndView mv = new ModelAndView(super.t + "/busisnes/busisness");
    try {
      if (entity.getiDisplayLength() == 0) entity.setiDisplayLength(10);                //默认长度5
      if (entity.getPageNo() <= 0) entity.setPageNo(1);                                  //默认页数1
      entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength());  //显示起始索引


      entity.setStatus("1");

      // 商机分类 查询
      List<HashMap> list = businessService.queryWapList(entity);

      // 查询商机分类
      mv.addObject("dataType", confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));

      // 商机列表 标题，id，时间
      mv.addObject("items", list);
      mv.addObject("title", title);
      mv.addObject("business", entity);
      mv.addObject("pageNo", entity.getPageNo());
      mv.addObject("size", entity.getiDisplayLength());
      mv.addObject("total", businessService.count(entity));
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "list", e);
    }
    return mv;
  }

  
	/**
	 * 全站搜索商机信息
	 *
	 * @return
	 */
	@RequestMapping("/search")
	@ResponseBody
	public Map<String, Object> search(Business entity, Integer pageNo, Integer pageSize, Integer fa, Integer ta, Integer fi,
	                           Integer ti) {
		Map<String, Object> resp = new HashMap<>();
		try {
			if(pageNo==null) pageNo = 1;
			if(pageSize==null) pageSize = 20;
			
			entity.setiDisplayStart((pageNo - 1) * pageSize);//查询起始值
			entity.setiDisplayLength(pageSize);//查询条数
			entity.setStatus("1");
			List list = businessService.searchM(entity, fa, ta, fi, ti);
			if(list!=null && list.size()>0){
				resp.put("statusCode", 200);
				resp.put("dataList",list);
			}else{
				resp.put("statusCode", 400);
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "全站搜索商机信息错误", e);
		}
		return resp;
	}
	
	/**
	 * 全站搜索商机信息记录总数
	 *
	 * @return
	 */
	@RequestMapping("/searchTotal")
	@ResponseBody
	public Map<String, Object> searchTotal(Business entity, Integer pageNo, Integer pageSize, Integer fa, Integer ta, Integer fi,
	                           Integer ti) {
		Map<String, Object> resp = new HashMap<>();
		try {
			resp.put("statusCode", 200);
			resp.put("total", businessService.searchTotal(entity, fa, ta, fi, ti));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "全站搜索商机信息记录总数错误", e);
		}
		return resp;
	}
	
  /**
   * 商机详细内容页面
   *
   * @param id
   * @return
   */
  @RequestMapping("/loadMore/{index}")
  @ResponseBody
  public Map<String, Object> loadMore(@PathVariable("index") int index, Business entity, String title) {
    Map<String, Object> resp = new HashMap<>();
    try {
      if (entity.getiDisplayLength() == 0) entity.setiDisplayLength(10);                //默认长度5
      if(index <= 0) index = 1;                                  //默认页数1
      entity.setPageNo(index);
      entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength());  //显示起始索引


      entity.setStatus("1");

      // 商机分类 查询
      List<HashMap> list = businessService.queryWapList(entity);
      if(list!=null && list.size()>0) {
        resp.put("statusCode", 200);
        resp.put("dataList", list);
      }else {
        resp.put("statusCode", 400);
      }
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "list", e);
    }
    return resp;
  }

  /**
   * 商机详细内容页面
   *
   * @param id
   * @return
   */
  @RequestMapping("/{id}")
  public ModelAndView detail(@PathVariable String id, String title) {
    ModelAndView mv = new ModelAndView(super.t + "/busisnes/busisnessDetail");
    Business business = businessService.queryById(id);


    if (null == business) {
      return new ModelAndView("/404.jsp");
    }
    Member member = super.getMember(false);
    if (member == null) {
      String telephone = business.getTelephone();
      if (telephone != null && telephone.length() > 3)
        business.setTelephone(telephone.substring(0, 3).concat("********"));
    } else if (orderService.queryHasOrder(member.getId(), String.valueOf(business.getId()))) {
      mv.addObject("has", "yes");
    } else {
      String telephone = business.getTelephone();
      if (telephone != null && telephone.length() > 3)
        business.setTelephone(telephone.substring(0, 3).concat("********"));
    }
    if (member != null) {
      CollectPK pk = new CollectPK(member.getId(), business.getId());
      collectService.isBusCollect(pk, business);
    }

    // 查询商机分类
    mv.addObject("dataType", confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));
    // 商机详情
    mv.addObject("business", business);
    mv.addObject("title", title);
    return mv;
  }

  
    /**
	 * 首页
	 * 初始化加盟信息
	 */
	@RequestMapping("/initJameng")
	public ModelAndView initJameng() {
		ModelAndView mv = new ModelAndView(super.t + "/jiameng");
		if(null != super.getMember()){//登录后 跳转到他要加盟 
		  mv.setViewName("redirect:/business/initHeJameng");
    }else{
      Date date = new Date();
      mv.addObject("addYear", date.getYear()+1900);// 当前年份
      mv.addObject("addMonth", date.getMonth()+1);// 当前月份
    }
		return mv;
	}
	
	/**
	 * 首页
	 * 初始化他要加盟信息 需要校验用户是否登录
	 */
	@RequestMapping("/initHeJameng")
	public ModelAndView initHeJameng(String title) {
      ModelAndView mv = new ModelAndView();
      if(null == getMember(true)) {
        mv.setViewName("redirect:/login");
      } else {
    	  mv.addObject("title", title);
          Date date = new Date();
          mv.addObject("addYear", date.getYear()+1900);// 当前年份
          mv.addObject("addMonth", date.getMonth()+1);// 当前月份
          mv.setViewName(super.t + "/hejiameng");
      }
      return mv;
	}
	
	
	
	/**
	 * @return /m/business/forSave?businesscode=1&summary=22
	 * @title
	 * @description: 保存我要加盟信息
	 * @author: 
	 * @date: 2013-10-15 16:53
	 */
	@RequestMapping("/forSave")
	@ResponseBody
	public Map<String, Object> forSave(Business entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			Member mbo = super.getMember(false);
			if(null != mbo) {
				entity.setCreater(mbo.getId());
			}
			String date = DateUtil.getCurrentTime();
			entity.setCreateTime(date);
			entity.setUpdateTime(date);
			entity.setStatus("0");
			if(businessService.save(entity) != null) {
				ipRecordService.save(IpUtil.getIp(request), "ipv4", "1");
				if(null != mbo) {
					memberService.updateMoney(mbo.getId(), GlobalConstant.SMONEY_BUSINESS_ADD);
				}
				jsonMap.put("msg", "success");
			} else {
				jsonMap.put("msg", "error");
			}
		} catch(Exception e) {
			jsonMap.put("msg", "error");
			BaseLog.e(this.getClass(), "保存我要加盟信息错误", e);
		}
		return jsonMap;
	}
  /**
   * @return
   * @title
   * @description: 校验加盟手机号是否已经存在
   * @author: wuzhiliang
   * @date: 2014-03-13 16:53
   */
  @RequestMapping("/checkUnickmobile")
  @ResponseBody
  public String checkUnickmobile(String telephone) {
    try {
      Business bo = new Business();
      bo.setTelephone(telephone.trim());
      Long count = businessService.count(bo);
      return count > 0 ? "false" : "true";
    } catch(Exception e) {
      // TODO: handle exception
    }
    return "true";
  }

}
